import React, { useEffect, useState } from 'react';
import {
    Card,
    Checkbox,
    Dialog,
    DialogProps, FormProps,
    MessagePlugin,
    Radio,
    Textarea,
    Switch,
    Tooltip,
    Link,
    PrimaryTable,
    Pagination,
    Message,

} from 'tdesign-react';
import { ErrorCircleFilledIcon, CheckCircleFilledIcon, CloseCircleFilledIcon } from 'tdesign-icons-react';

import axios from 'axios';
import { flushSync } from 'react-dom';

import {
    Button,
    Cascader,
    DatePicker,
    Form,
    Input,
    InputNumber,
    Mentions,
    Select,
    TreeSelect,
    Segmented,
    Space,
    Table,
    Tag,
    Modal,
    Tabs,
    Menu,
} from 'antd';

import type { PaginationProps, TableProps } from 'antd';

import { message } from 'antd';
import TabPane from 'antd/es/tabs/TabPane';
import Sider from 'antd/es/layout/Sider';
axios.defaults.baseURL = 'http://127.0.0.1:3000/zlq'


export default function Dictionary() {
    const [form] = Form.useForm()

    const [visible, setVisible] = useState(false);
    const handleClick = () => {
        setVisible(true);
    };
    const onConfirm: DialogProps['onConfirm'] = async (context) => {
        let form = {
            dictionary_cate: dictionary_cate,
            num: num,
            name: name,
            content: content,
            state: state
        }
        let { data: { code } } = await axios.post('dictionaryadd', form)
        if (code == 200) {
            getDictionaryList()
            setDctionary_cate("")
            setNum("")
            setName("")
            setContent("")
            setState("")
        }
        console.log('点击了确认按钮', context);
        setVisible(false);
    };
    const onCancel: DialogProps['onCancel'] = (context) => {

        setDctionary_cate("")
        setNum("")
        setName("")
        setContent("")
        setState("")
        setVisible(false);
        console.log('点击了取消按钮', context);
    };
    const onClickCloseBtn: DialogProps['onCloseBtnClick'] = (context) => {

        setDctionary_cate("")
        setNum("")
        setName("")
        setContent("")
        setState("")
        console.log('点击了关闭按钮', context);
    };
    const onKeydownEsc: DialogProps['onEscKeydown'] = (context) => {
        console.log('按下了ESC', context);
    };
    const onClickOverlay: DialogProps['onOverlayClick'] = (context) => {
        console.log('点击了蒙层', context);
    };
    const handleClose: DialogProps['onClose'] = (context) => {
        console.log('关闭弹窗，点击关闭按钮、按下ESC、点击蒙层等触发', context);
        setVisible(false);
    };
    // const name = Form.useWatch('name', form);
    const gender = Form.useWatch('gender', form);
    // console.log('name', name);
    console.log('gender', gender);

    const onSubmit: FormProps['onSubmit'] = (e) => {
        console.log(e);
        if (e.validateResult === true) {
            MessagePlugin.info('提交成功');
        }
    };

    const onReset: FormProps['onReset'] = (e) => {
        console.log(e);
        MessagePlugin.info('重置成功');
    };

    const setMessage = () => {
        console.log(form);
        form.setFields([
            { name: 'name', status: 'error', validateMessage: { type: 'error', message: '输入有误' } },
            { name: 'birthday', status: 'warning', validateMessage: { type: 'warning', message: '时间有误' } },
        ]);
    };
    const [dictionary_cateList, setDictionary_cateList] = useState([]);
    const [groupingList, setGroupingList] = useState([]);
    const [dictionaryList, setDictionaryList] = useState([])

    const [id, setId] = useState('')
    const [dictionary_cate, setDctionary_cate] = useState('')
    const [num, setNum] = useState('')
    const [name, setName] = useState('')
    const [content, setContent] = useState('')
    const [state, setState] = useState('')

    const getDictionary_cate = async () => {
        let { data: { code, dictionary_cateList } } = await axios.get(`/dictionary_cateList?name=${dictionary_cateName}`)
        if (code == 200) {
            setDictionary_cateList(dictionary_cateList)
            setDictionary_data(dictionary_cateList)
        }
    }

    let [so_name, setSo_Name] = useState('')
    const getDictionaryList = async () => {
        let { data: { code, dictionaryList, total } } = await axios.get(`/dictionaryList?page=${page}&pagesize=${pageSize}&name=${so_name}&dictionary_cate=${indexs}`)
        if (code == 200) {
            setTotal(total)
            setDictionaryList(dictionaryList)
            setData(dictionaryList)
        }
    }

    let page = 1
    let pageSize = 2
    let [total, setTotal] = useState(0)

    const onChange: PaginationProps['onChange'] = (pageInfo) => {
        page = pageInfo.current
        pageSize = pageInfo.pageSize
        getDictionaryList()
        console.log(pageInfo);
    };
    const onPageSizeChange: PaginationProps['onPageSizeChange'] = (size) => {
        pageSize = size
        getDictionaryList()
        console.log('page-size:', size);
    };
    const onCurrentChange: PaginationProps['onCurrentChange'] = (index, pageInfo) => {
        page = index
        getDictionaryList()
        console.log(`转到第${index}页`);
        console.log(pageInfo);
    };



    const getName = (e) => {
        if (e.key === 'Enter') {  // 判断是否是回车键
            console.log('回车键被按下，执行搜索');
            // 在这里触发搜索逻辑
            // 例如，调用一个搜索 API，或者根据 so_name 进行搜索
            getDictionaryList()
        }
    };

    const getEdit = (id: any) => {
        showModal()
        console.log(id);
        setId(id._id);
        setDctionary_cate(id.dictionary_cate);
        setContent(id.content);
        setNum(id.num);
        setState(id.state);
        setName(id.name);
        setVisible(true);
    };

    const getUpdate = async () => {
        let form = {
            _id: id,
            dictionary_cate: dictionary_cate._id,
            num: num,
            name: name,
            content: content,
            state: state
        }
        let { data: { code } } = await axios.post('dictionaryupd', form)
        if (code == 200) {
            getDictionaryList()
            setId('')
            setDctionary_cate("")
            setNum("")
            setName("")
            setContent("")
            setState("")
            handleOk()
        }
    }

    const getAdd = async () => {
        let form = {
            dictionary_cate: dictionary_cate._id,
            num: num,
            name: name,
            content: content,
            state: state
        }

        let { data: { code } } = await axios.post('dictionaryadd', form)
        if (code == 200) {
            getDictionaryList()
            setDctionary_cate("")
            setNum("")
            setName("")
            setContent("")
            setState("")
            handleOk()
        }
    }

    const [messageApi, contextHolder] = message.useMessage();

    //词条删除
    const getDel = async (id) => {
        let { data: { code } } = await axios.delete(`managementdel?_id=${id}`)
        if (code == 200) {
            getDictionaryList()
        }
    }

    const variant = Form.useWatch('variant', form);

    // 提交表单时的操作
    const onFinish = (values) => {
        console.log(values);
        // 你可以在这里发送这些数据到后台
    };

    interface DataType {
        key: string;
        name: string;
        num: number;
        address: string;
        tags: string[];
    }

    //词条表格
    const columns: TableProps<DataType>['columns'] = [
        {
            title: '词条编码',
            dataIndex: 'num',
            key: 'num',
            render: (text) => <a>{text}</a>,
        },
        {
            title: '词条名称',
            dataIndex: 'name',
            key: 'name',
        },

        {
            title: '启用状态',
            key: 'tags',
            dataIndex: 'tags',
            render: (_, row) => (
                <Space size="middle">
                    {row.state ? (
                        <p style={{ color: "green" }}>启用</p>
                    ) : (
                        <p style={{ color: "red" }}>禁用</p>
                    )}
                </Space>
            ),
        },
        {
            title: '更新时间',
            dataIndex: 'time',
            key: 'time',
            render: (text) => {
                // 通过 Date 对象来格式化时间
                const date = new Date(text);
                const formattedDate = date.toLocaleDateString('zh-CN', {
                    year: 'numeric',
                    month: 'long',
                    day: 'numeric',
                    hour: '2-digit',
                    minute: '2-digit',
                    second: '2-digit',
                });
                return formattedDate; // 返回格式化后的日期字符串
            },
        },
        {
            title: '词条内容',
            dataIndex: 'content',
            key: 'content',
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <Space size="middle">
                    <a onClick={() => { getEdit(record) }}>编辑</a>
                    <a style={{ color: "red" }} onClick={() => { getDel(record._id) }}>删除</a>
                </Space>
            ),
        },
    ];

    const [data, setData] = useState<DataType[]>([]);

    //词条回显
    useEffect(() => {
        form.setFieldsValue({
            name: name,
            dictionary_cate: dictionary_cate._id || "",
            content: content,
            num: num,
            state: state,
        });
    }, [name, dictionary_cate, content, num, state]);

    const [selectedRowKeys, setSelectedRowKeys] = useState([]);
    const onSelectChange = (newSelectedRowKeys) => {
        console.log('selectedRowKeys changed: ', newSelectedRowKeys);
        setSelectedRowKeys(newSelectedRowKeys);
    };
    const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange,
    };


    //新增词条弹框
    const [isModalOpen, setIsModalOpen] = useState(false);

    const showModal = () => {
        setIsModalOpen(true);
    };

    const handleOk = () => {
        setId('')
        setDctionary_cate("")
        setNum("")
        setName("")
        setContent("")
        setState("")
        setIsModalOpen(false);
    };

    const handleCancel = () => {
        setIsModalOpen(false);
    };

    const { TabPane } = Tabs;

    //词条权限分类
    // 用来存储当前选中的分类
    const [selectedCategory, setSelectedCategory] = useState('category1');
    // 用来存储搜索的关键字
    const [searchQuery, setSearchQuery] = useState('');
    // 存储各个分类的搜索选项
    const [selectedOption, setSelectedOption] = useState(null);


    // 处理分类选择
    const handleCategoryChange = (key) => {
        setSelectedCategory(key);
        setSearchQuery('');  // 切换分类时清空搜索框
        setSelectedOption(null);  // 清空已选选项
    };

    const getGroupingAdd = async () => {
        let form = {
            name: dictionary_cateName,
        }
        let { data: { code } } = await axios.post('groupingadd', form)
        if (code == 200) {
            getDictionary_cate()
            setDictionary_cateName('')
        }
    }

    const grouping_columns: TableProps<DataType>['columns'] = [
        {
            title: '分组名称',
            dataIndex: 'name',
            key: 'name',
        },
    ];

    const [dictionary_data, setDictionary_data] = useState<DataType[]>([]);
    const [dictionary_cateName, setDictionary_cateName] = useState('')
    const [dictionary_cate_id, setDictionary_cate_id] = useState('')

    const getGroupingEdit = (id) => {
        setDictionary_cate_id(id._id)
        setDictionary_cateName(id.name)
    }

    const Dictionary_cateSo = async (e) => {
            if (e.key === 'Enter') {  // 判断是否是回车键
                console.log('回车键被按下，执行搜索');
                // 在这里触发搜索逻辑
                // 例如，调用一个搜索 API，或者根据 so_name 进行搜索
                getDictionary_cate()
            }
    }

    const getDictionary_cateDel = async (id) => {
        let { data: { code } } = await axios.delete(`dictionary_catedel?_id=${id}`)
        if (code == 200) {
            getDictionary_cate()
        }
    }

    let [indexs, setIndexs] = useState('')
    // 分类搜索
    const handleCategoryClick = (e) => {
        if (indexs = e._id) {
            setIndexs(e._id)
            getDictionaryList()
        }
        console.log(indexs);
    };
    const [filteredData, setFilteredData] = useState(data);

    useEffect(() => {
        getDictionary_cate()
        getDictionaryList()
    }, [])
    return (
        <div style={{ display: "flex" }}>
            <div style={{ marginRight: "20px", width: "500px" }}>
                <Card bordered title="字典列表">
                    <div style={{ padding: '20px', height: "528px" }}>
                        <Form.Item
                            name="groupingName"
                            rules={[{ required: true, message: 'Please input Entry!' }]}
                        >
                            <Input placeholder='请输入...' value={dictionary_cateName} onChange={(e) => setDictionary_cateName(e.target.value)}  onKeyDown={Dictionary_cateSo} style={{ marginRight: "10px" }} />
                        </Form.Item>
                        <Sider>
                            <Menu
                                mode="inline"
                                defaultSelectedKeys={['1']}
                                style={{ height: '100%', borderRight: 0,}}
                            >
                                {
                                    dictionary_data.map((d) => {
                                        return (
                                            <Menu.Item key={d._id} onClick={() => handleCategoryClick(d)}>
                                                {d.name}
                                            </Menu.Item>
                                        )
                                    })
                                }
                            </Menu>
                        </Sider>
                    </div>
                </Card>
            </div>

            <div style={{ height: "500px" }}>
                <Card
                    title="字典详情"
                    actions={
                        <Button onClick={showModal}>新增词条</Button>
                    }
                    bordered
                    headerBordered
                    style={{ height: "600px", width: "1000px" }}
                >
                    <Modal title="编辑词条" closable={false} open={isModalOpen} onOk={handleOk} onCancel={handleCancel} footer={null}>
                        <div style={{ maxWidth: 600 }}>
                            <Form
                                form={form}
                                variant={variant || 'filled'}
                                initialValues={{
                                    variant: 'filled',
                                    id: id,
                                    dictionary_cate: dictionary_cate,
                                    num: num,
                                    name: name,
                                    content: content,
                                    state: state
                                }}
                                onFinish={onFinish}
                            >
                                {/* grouping 字段 */}
                                <Form.Item
                                    label="词条分组"
                                    name="grouping"
                                    rules={[{ required: true, message: 'Please input Grouping!' }]}
                                >
                                    <Select
                                        value={dictionary_cate?._id} // 如果 grouping 是对象，确保它有 _id
                                        onChange={(e: string) => {
                                            const selectedDictionary_cate = dictionary_cateList.find(item => item._id === e);
                                            setDctionary_cate(selectedDictionary_cate); // 更新 grouping 为对象
                                        }}
                                    >
                                        {dictionary_cateList.map((item, index) => (
                                            <Select.Option key={index} value={item._id} name="grouping">
                                                {item.name}
                                            </Select.Option>
                                        ))}
                                    </Select>
                                </Form.Item>


                                {/* entry 字段 */}
                                <Form.Item
                                    label="词条编码"
                                    name="num"
                                    rules={[{ required: true, message: 'Please input Entry!' }]}
                                >
                                    <Input value={num} onChange={(e) => setNum(e.target.value)} />
                                </Form.Item>

                                {/* name 字段 */}
                                <Form.Item
                                    label="词条名称"
                                    name="name"
                                    rules={[{ required: true, message: 'Please input Name!' }]}
                                >
                                    <Input value={name} onChange={(e) => setName(e.target.value)} />
                                </Form.Item>

                                {/* content 字段 */}
                                <Form.Item
                                    label="词条内容"
                                    name="content"
                                    rules={[{ required: true, message: 'Please input Content!' }]}
                                >
                                    <Input.TextArea rows={5} value={content} onChange={(e) => setContent(e.target.value)} />
                                </Form.Item>

                                {/* state 字段 */}
                                <Form.Item label="启用状态" name="state">
                                    <Radio.Group onChange={(e) => setState(e)} value={state}>
                                        <Radio value={true}>启用</Radio>
                                        <Radio value={false}>禁用</Radio>
                                    </Radio.Group>
                                </Form.Item>

                                <Form.Item wrapperCol={{ offset: 6, span: 16 }}>
                                    {
                                        id ? <Button type="primary" htmlType="submit" onClick={() => { getUpdate() }}>
                                            编辑
                                        </Button> :
                                            <Button type="primary" htmlType="submit" onClick={() => { getAdd() }}>
                                                新增
                                            </Button>
                                    }
                                    <Button type="primary" htmlType="submit" onClick={() => { handleOk() }}>
                                        取消
                                    </Button>
                                </Form.Item>
                            </Form>
                        </div>
                    </Modal>

                    <div style={{ display: 'flex' }}>
                        <Form.Item label="字典名称" name="so_name" initialValue={so_name}>
                            <Input
                                placeholder='请输入...' 
                                value={so_name}
                                onChange={(e) => setSo_Name(e.target.value)}  // 更新输入框的值
                                onKeyDown={getName}  // 监听键盘事件，判断是否是回车键
                            />
                        </Form.Item>
                    </div>

                    <div>
                        <Table<DataType> pagination={false} rowSelection={rowSelection} columns={columns} dataSource={data} />
                    </div>
                    <Pagination
                        total={total}
                        defaultPageSize={pageSize}
                        onChange={onChange}
                        onCurrentChange={onCurrentChange}
                        onPageSizeChange={onPageSizeChange}
                    />
                </Card>
            </div >
        </div >
    );
}